<template>
  <div class="app-container">
    <el-form ref="trainingLevel" :model="trainingLevel" :rules="rules" label-width="120px">
      <div style="width: 450px">

<!--        <el-form-item label="靶场ID" prop="trainingId" >-->
<!--          <el-input v-model="trainingLevel.trainingId" clearable />-->
<!--        </el-form-item>-->

        <el-form-item label="靶场名称" prop="trainingName" >
          <el-input v-model="trainingLevel.trainingName" clearable />
        </el-form-item>

        <el-form-item label="靶场种类" prop="parentId">
          <el-input v-model="trainingLevel.parentId" placeholder="若为一级分类请输入 0" clearable />
        </el-form-item>

      </div>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="addOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import training_level from '../../api/training_level'

export default {
  data() {
    const validateName = (rule, value, callback) => {
      // 区分是新增操作还是修改操作,根据有没有id来区分
      // 修改，要区分用户填写的名字是不是跟原本的名字一样的
      if (this.trainingLevel.id) {
        if (this.oldName !== value) {
          training_level.nameIsExit(value).then(res => {
            if (res.data === false) {
              callback()
            } else {
              callback(new Error('该名称已经被使用'))
            }
          })
        }
        callback()
      } else {
        // 新增
        // 给后端发起一个请求，查询该用户名是否存在
        training_level.nameIsExit(value).then(res => {
          if (res.data === false) {
            callback()
          } else {
            callback(new Error('该名称已经被使用'))
          }
        })
      }
    }
    const trainingType = (rule, value, callback) => {
      // 区分是新增操作还是修改操作,根据有没有id来区分
      // 修改，要区分用户填写的名字是不是跟原本的名字一样的
      if (this.trainingLevel.id) {
        if (this.oldName !== value && value !=0) {
          training_level.nameIsExit(value).then(res => {
            if (res.data === true) {
              callback()
            } else {
              callback(new Error('该靶场种类不存在'))
            }
          })
        }
        callback()
      } else {
        // 新增
        // 给后端发起一个请求，查询该用户名是否存在
        training_level.nameIsExit(value).then(res => {
            if (res.data === true) {
              callback()
            } else {
              if (value!=0){
                callback(new Error('该靶场种类不存在'))
              }
              else {
                callback()
              }
            }
        })
      }
    }
    // const validateID = (rule, value, callback) => {
    //   // 区分是新增操作还是修改操作,根据有没有id来区分
    //   // 修改，要区分用户填写的id是不是跟原本的id一样的
    //   if (this.trainingLevel.id) {
    //     if (this.oldID !== value) {
    //       training_level.idIsExit(value).then(res => {
    //         if (res.data === true) {
    //           callback()
    //         } else {
    //           callback(new Error('该ID已存在'))
    //         }
    //       })
    //     }
    //   } else {
    //     // 新增
    //     // 给后端发起一个请求，查询该id是否存在
    //     training_level.idIsExit(value).then(res => {
    //       if (res.data === false) {
    //         callback()
    //       } else {
    //         callback(new Error('该ID已存在'))
    //       }
    //     })
    //   }
    // }
    return {
      trainingLevel: {
      },
      saveBtnDisabled: false,
      oldName: null,
      rules: {
        trainingName: [
          { required: true, message: '请输入靶场名称', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请输入靶场种类', trigger: 'blur' },
          { validator: trainingType, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.$route.params && this.$route.params.id) {
      const id = this.$route.params.id
      this.selectTrainingLevelById(id)
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.trainingLevel.avatar = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 20

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 20MB!')
      }
      return isJPG && isLt2M
    },
    addOrUpdate() {
      this.$refs['trainingLevel'].validate((valid) => {
        if (valid) {
          console.log('if  ' + this.trainingLevel.id)
          if (this.trainingLevel.id != null && this.trainingLevel.id.length > 0) {
            this.updateTrainingLevel()
          } else {
            this.addTrainingLevel()
          }
        } else {
          // this.saveBtnDisabled = true
          this.$message.error('校验不通过！请重试！')
          console.log('error submit!!')
          return false
        }
      })
    },
    addTrainingLevel() {
      training_level.add(this.trainingLevel).then(res => {
        this.$message.success(res.message)
        this.$router.push({ path: '/trainingLevel/list' })
      })
    },
    updateTrainingLevel() {
      training_level.add(this.trainingLevel).then(res => {
        this.$message.success(res.message)
        this.$router.push({ path: '/trainingLevel/list' })
      })
    },
    selectTrainingLevelById(id) {
      training_level.selectTrainingLevelById(id).then(res => {
        this.trainingLevel = res.data[0]
        this.oldName = this.trainingLevel.trainingName
        // this.oldID = this.trainingLevel.trainingId
      })
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
